package net.simpleos.backend.permission;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import net.simpleframework.ado.db.ExpressionValue;
import net.simpleframework.ado.db.IQueryEntitySet;
import net.simpleframework.core.ado.IDataObjectQuery;
import net.simpleframework.web.page.component.ComponentParameter;
import net.simpleframework.web.page.component.ui.tree.AbstractTreeBean;
import net.simpleframework.web.page.component.ui.tree.AbstractTreeHandle;
import net.simpleframework.web.page.component.ui.tree.AbstractTreeNode;
import net.simpleframework.web.page.component.ui.tree.TreeNode;
import net.simpleos.SimpleosUtil;
import net.simpleos.backend.menu.MenuNavBean;
import net.simpleos.backend.menu.MenuNavUtils;
import net.simpleos.utils.StringsUtils;

public class DefaultPlatformMenuTreeHandle extends AbstractTreeHandle {

	@Override
	public Collection<? extends AbstractTreeNode> getTreenodes(final ComponentParameter compParameter, final AbstractTreeNode treeNode) {
		final String jobId = compParameter.getRequestParameter("jobId");
		if (StringsUtils.isBlank(jobId)) {
			return null;
		}
		final AbstractTreeBean treeBean = (AbstractTreeBean) compParameter.componentBean;
		final List<PermissionBean> list = IDataObjectQuery.Utils.toList(SimpleosUtil.getTableEntityManager(SimpleosUtil.applicationModule,
				PermissionBean.class).query(new ExpressionValue("job_id=?", new Object[] { jobId }), PermissionBean.class));
	
		final Collection<AbstractTreeNode> _treeNode = new ArrayList<AbstractTreeNode>();
		if (treeNode != null)
			return null;

		final TreeNode root = new TreeNode(treeBean, treeNode, "功能菜单");
		root.setOpened(true);
		_treeNode.add(root);
		buildMenu(root.getChildren(), root, treeBean, 0, list);
		return _treeNode;
	}

	public int hasMenu(final List<PermissionBean> list, final MenuNavBean item) {
		for (final PermissionBean bean : list) {
			if (bean.getMenu_name().equals(item.getName())) {
				return 1;
			}
		}
		return 0;
	}

	private void buildMenu(final Collection<AbstractTreeNode> menuList, final TreeNode root, AbstractTreeBean treeBean, Object parentId,
			final List<PermissionBean> list) {
		final IQueryEntitySet<MenuNavBean> qs = MenuNavUtils.appModule.queryBean("mark=0 and parentid=" + parentId + " order by oorder",
				MenuNavBean.class);
		MenuNavBean menu = null;
		while ((menu = qs.next()) != null) {
			if (menu.getText().equals("-")) {
				continue;
			}
			final TreeNode subTreeNode = new TreeNode(treeBean, root, menu.getText());
			subTreeNode.setId(menu.getName());
			subTreeNode.setCheck(hasMenu(list, menu));
			menuList.add(subTreeNode);
			buildMenu(subTreeNode.getChildren(), subTreeNode, treeBean, menu.getId(), list);
		}
	}

}
